/**
 * 根据后端返回的文件线上地址下载文件
 * @param url {String} 文件地址
 * @param fileName {String} 文件名称
 * @param type {String} 文件后缀
 */
export function fileLinkToStreamDownload(url, fileName, type) {
  let reg =
    /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~%\-]+).)+([A-Za-z0-9-~\/])+$/;
  if (!reg.test(url)) {
    throw new Error("传入参数不合法,不是标准的文件链接");
  } else {
    let xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    xhr.setRequestHeader("Content-Type", `application/${type}`);
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (this.status == 200) {
        //接受二进制文件流
        const blob = this.response;
        downloadExportFile(blob, fileName, type);
      }
    };
    xhr.send();
  }
}

const downloadExportFile = (blob, tagFileName, fileType) => {
  let downloadElement = document.createElement("a");
  let href = blob;
  if (typeof blob == "string") {
    downloadElement.target = "_blank";
  } else {
    href = window.URL.createObjectURL(blob); //创建下载的链接
  }
  downloadElement.href = href;
  downloadElement.download =
    tagFileName + dayjs(new Date()).format("YYYYMMDDHHmmss") + "." + fileType; //下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); //点击下载
  document.body.removeChild(downloadElement); //下载完成移除元素
  if (typeof blob != "string") {
    window.URL.revokeObjectURL(href); //释放掉blob对象
  }
};
// 防抖
export function debounce(fn, delay) {
  let timer = null;
  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
    }, delay);
  };
}
// 节流
export function throttle(fn, delay) {
  let timer = null;
  return function () {
    if (!timer) {
      timer = setTimeout(() => {
        fn.apply(this, arguments);
        timer = null;
      }, delay);
    }
  };
}
/**
 * 年月日处理
 * @param date {String} 时间
 * @param fmt {String}  需要格式(yyyy-MM-dd hh:mm:ss)
 */
export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + "";
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      );
    }
  }
  return fmt;
}
function padLeftZero(str) {
  return ("00" + str).substr(str.length);
}
/**
 * 该文件提供日期时间处理功能，包括计算一小时前和一天前的日期时间。
 * 使用方法：引入本模块后，调用相应函数即可获取所需日期时间。
 * 注意：本模块仅适用于处理日期时间相关操作。
 * @param time {String} 时间戳
 */
export function formatTime(time) {
  let now = new Date().getTime();
  let diff = (now - time) / 1000;
  if (diff < 60) {
    return "刚刚";
  } else if (diff < 60 * 60) {
    return Math.floor(diff / 60) + "分钟前";
  } else if (diff < 60 * 60 * 24) {
    return Math.floor(diff / 60 / 60) + "小时前";
  } else if (diff < 60 * 60 * 24 * 30) {
    return Math.floor(diff / 60 / 60 / 24) + "天前";
  } else {
    return formatDate(new Date(time), "yyyy-MM-dd hh:mm:ss");
  }
}
//千分位逗号并且整数或负数补00
export function formatNumber(num) {
  if (num === null) {
    return null;
  }
  if (num === undefined) {
    return undefined;
  }
  if (num === "") {
    return "";
  }
  num = num.toString();
  if (num.indexOf(".") === -1) {
    num = num + ".00";
  }
  num = num.replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
  return num;
}